import base64
import hmac

from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

from qiniu import Auth
#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid
from hashlib import sha256
import urllib

from myapp.myser import *


class UserInfo(APIView):

    def get(self,request):
        uid = request.GET.get('uid')
        user = User.objects.filter(id=uid).first()

        ser = UserSer(user)
        return Response(ser.data)

#定义地址和端口
host = '127.0.0.1'
port = 6379

#建立redis连接
r = redis.Redis(host=host,port=port)

class QiNiu(APIView):

    def get(self,request):
        q = Auth('mARrCH5xfDiTTrkDVYo0wS40bOAy00zAtLZvbyfA','uHl5vArUQDy-dvn30AR5Rhil-9I2rXXXUXGTWvS0')

        token = q.upload_token('mdm')
        res = {'token':token}

        return Response(res)




class UploadFile(View):
    # 头像展示
    def get(self,request):
        uid = request.GET.get('uid')
        user = User.objects.filter(id=uid).first()

        return HttpResponse(json.dumps({'filename':user.img},ensure_ascii=False),content_type='application/json')


    # 文件上传接口
    def post(self,request):
        uid = request.POST.get('uid')
        myfile = request.FILES.get("file")

        f = open(os.path.join(UPLOAD_ROOT,'',str(uid)+".jpg"),'wb')
        for chunk in myfile.chunks():
            f.write(chunk)

        # 关闭
        f.close()
        user = User.objects.filter(id=uid).first()
        user.img = str(uid)+".jpg"
        user.save()

        return HttpResponse(json.dumps({'filename':str(uid)+".jpg"},ensure_ascii=False),content_type='application/json')



class DingDing_back(APIView):

    def get(self,request):
        code = request.GET.get('code')
        # 获取时间戳
        t = time.time()
        timestamp = str(int(round(t * 1000)))
        # 构造签名  appSecret
        appSecret = "eMd7zuSSTfsXcbBg2SSBIODnZlDSwv8kWq_RStPudmEDTyEesp-U3UJoLzPOAnmB"
        signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'),digestmod=sha256).digest())
        # 请求当前用户的信息
        headers = {'Content-Type':'application/json'}
        url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey="+"dingoasyyehyz5u1fzgmcv&timestamp="+timestamp+'&signature='+urllib.parse.quote(signature.decode('utf-8'))
        payload = {'tmp_auth_code': code}
        res = requests.post(url=url,data=json.dumps(payload),headers=headers)
        res_dict = json.loads(res.text)
        print(res_dict['user_info']['nick'])

        user = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
        ding_id = ""
        user_id = ""
        if user:
            # 登录过
            ding_id = user.username
            user_id = user.id
        else:
            # 未登录
            u = User(username=str(res_dict['user_info']['nick']), password="", type=0, img="!")
            u.save()

            sinauser = User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
            ding_id = sinauser.username
            user_id = sinauser.id


        return redirect('http://127.0.0.1:8080?ding_id=' + ding_id + '&user_id=' + str(user_id))




# 微博回调
def weibo_back(request):
    code = request.GET.get('code')
    url = "https://api.weibo.com/oauth2/access_token"
    data = {
        "client_id":2308045722,
        "client_secret":"4e66ffac3774129ab6c37dc27b1d121a",
        "grant_type":"authorization_code",
        "redirect_uri":"http://127.0.0.1:8000/weibo_back",
        "code":code
    }

    res = requests.post(url=url,data=data)
    rdata = json.loads(res.text)
    # 查询是否用微博登录
    user = User.objects.filter(username=str(rdata['uid'])).first()
    sina_id = ""
    user_id = ""
    if user:
        # 登录过
        sina_id = user.username
        user_id = user.id
    else:
        # 未登录
        u = User(username=str(rdata['uid']),password="",type=0,img="!")
        u.save()

        sinauser = User.objects.filter(username=str(rdata['uid'])).first()
        sina_id = sinauser.username
        user_id = sinauser.id
    return redirect('http://127.0.0.1:8080?sina_id='+sina_id+'&user_id='+str(user_id))


#定义验证码
class MyCode(View):

    #定义随机验证颜色
    def get_random_color(self):
        R = random.randrange(255)
        G = random.randrange(255)
        B = random.randrange(255)

        return (R,G,B)

    #随机验证码
    def get(self,request):
        #画布
        img_size = (110,50)
        #定义颜色类型
        image = Image.new("RGB",img_size,'white')
        #画笔
        draw = ImageDraw.Draw(image,'RGB')
        #定义随机字符串
        source = '0123456789'
        #容器，用来接收随机字符串
        code_str = ''
        for i in range(4):
            #获取字体颜色
            text_color = self.get_random_color()
            #获取字符串
            tmp_num = random.randrange(len(source))
            #获取字符集
            random_str = source[tmp_num]
            #添加到容器中
            code_str += random_str
            #绘制
            draw.text((10+30*i,20),random_str,text_color)
        #文件流缓冲区
        buf = io.BytesIO()
        #将图片保存到缓冲区
        image.save(buf,'png')
        #将随机码存储到redis中
        r.set('code',code_str)
        request.session['code'] = code_str

        return HttpResponse(buf.getvalue(),'image/png')




#md5加密方法
def make_password(mypass):
    #生成md5对象
    md5 = hashlib.md5()
    #定义加密对象
    sign_str = mypass
    #转码
    sign_utf8 = str(sign_str).encode(encoding="utf-8")
    #加密操作
    md5.update(sign_utf8)
    #生成密文
    md5_server = md5.hexdigest()
    return md5_server

#注册接口
class Register(APIView):

    def get(self,request):

        #接收参数
        username = request.GET.get('username','未收到用户名')
        password = request.GET.get('password','未收到密码')
        code = request.GET.get('code','未收到验证码')

        #从redis中获取生成好的验证码
        # mycode = r.get('code')
        # #转码
        # mycode = mycode.decode('utf-8')

        # session_code = request.session.get('code',None)
        # print(session_code)
        mycode = request.session.get('code')
        print(mycode)

        #判断验证码是否输入正确
        if code != mycode:
            res = {}
            res['code'] = 405
            res['message'] = '验证码输入错误'
            return Response(res)

        #排重操作
        user = User.objects.filter(username=username).first()

        if user:
            res = {}
            res['code'] = 405
            res['message'] = '用户已经存在'
            return Response(res)
        
        #进行入库操作
        user = User(username=username,password=make_password(password),img='',type=0)
        # 保存
        user.save()

        #返回结果
        res = {}
        res['code'] = 200
        res['message'] = '注册成功'
        return Response(res)


class Login(APIView):

    def get(self,request):
        username = request.GET.get('username','用户名不存在')
        password = request.GET.get('password','密码不存在')

        user = User.objects.filter(username=username,password=make_password(password)).first()
        
        if user:
            res = {}
            res['code'] = 200
            res['message'] = '登录成功'
            res['username'] = user.username
            res['uid'] = user.id
            return Response(res)
        else:
            res = {}
            res['code'] = 405
            res['message'] = '用户名或密码错误'
            return Response(res)
            






